package com.zhongxi.guoyuan.view.personalCenter;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.TitleCateAdapter;
import com.zhongxi.guoyuan.adapter.personCenter.ClearWeedExchangeAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;

import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.BaseResult;
import com.zhongxi.guoyuan.entity.clearweed.ClearWeedGood;
import com.zhongxi.guoyuan.entity.clearweed.ClearWeedResult;
import com.zhongxi.guoyuan.entity.projectItem.ProjectItemData;
import com.zhongxi.guoyuan.entity.projectItem.ProjectItemResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.view.rewardCoin.HMActivity;
import com.zhongxi.guoyuan.widget.goldshop.NoScrollGridView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ClearWeedExchangeActivity extends BaseActivity implements View.OnClickListener, ClearWeedExchangeAdapter.OnItemClickListener {


    @Bind(R.id.rl)
    RelativeLayout rl;
    @Bind(R.id.tv_cate_title)
    TextView tvCateTitle;
    @Bind(R.id.ll_allCate)
    LinearLayout llAllCate;
    @Bind(R.id.et_text_cancel)
    TextView etTextCancel;
    @Bind(R.id.iv_shoper_search)
    ImageView ivShoperSearch;

    EditText etCoinShop;
    @Bind(R.id.et_hint_text)
    TextView etHintText;
    @Bind(R.id.et_clear)
    TextView etClear;
    @Bind(R.id.rela_reward_search)
    RelativeLayout relaRewardSearch;
    @Bind(R.id.tv_exchange_recently)
    TextView tvExchangeRecently;
    @Bind(R.id.tv_exchange_newest)
    TextView tvExchangeNewest;
    @Bind(R.id.tv_exchange_sales)
    TextView tvExchangeSales;
    @Bind(R.id.clearweed_iv_search)
    ImageView ivTitleSearch;

    RecyclerView recyclerView;
    private ImageView ivBack;
    private TextView tvTitle;

    private LinearLayoutManager layoutManager;
    private ClearWeedExchangeAdapter adapter;

    int lastItem;
    private String trim;
    private int orderby = 1;
    private String cateid = "0";
    private String longitude;
    private String latitude;
    private String type;

    private List<ProjectItemData> itemResultList = new ArrayList<>();
    private List<ClearWeedGood> clearWeedGoodList = new ArrayList<>();
    private JSONObject storeInfo;
    private boolean isLoading;
    private boolean issearch;
    private ClearWeedResult clearWeedResult;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_clear_weed_exchange);
        ButterKnife.bind(this);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        ivBack = (ImageView) findViewById(R.id.ivBack);
        recyclerView = (RecyclerView) findViewById(R.id.recycleView_exchange);
        etCoinShop = (EditText) findViewById(R.id.et_coin_shop);
        tvTitle.setText("豆豆兑换");
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

    }

    @Override
    protected void initData() {
        super.initData();
        itemResultList.add(0, new ProjectItemData("全部分类", true));

        adapter = new ClearWeedExchangeAdapter(this);
        recyclerView.setAdapter(adapter);
        trim = etCoinShop.getText().toString().trim();
        longitude = MyApplication.getInstance().getLongitude();
        latitude = MyApplication.getInstance().getLatitude();
        getCate();
    }

    private void getCate() {
        type = "cate";
        getServer(Url.CLEARWEED_CATE, null, "", false, null, "get");
    }

    /**
     * orderby
     * cateid
     * lng
     * lat
     * content
     */

    public void getSearchData() {
        issearch = true;
        type = "data";
        Map<String, String> map = new HashMap<>();
        map.put("orderby", orderby + "");
        map.put("cateid", cateid);
        map.put("lng", longitude);
        map.put("lat", latitude);
        map.put("content", trim);
        String string = "&page=" + pageNum;
        getServer(Url.CLEARWEED_SEARCH, map, string, false, null, "post");
    }

    public void getData() {
        issearch = false;
        type = "data";
        String str = "&page=" + pageNum + "&orderby=" + orderby + "&cateid=" + cateid + "&lng=" + longitude + "&lat=" + latitude;
        getServer(Url.CLEARWEED_GOODLIST, null, str, false, null, "get");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastItem + 1 == adapter.getItemCount() && !isLoading
                        ) {
                    if (clearWeedResult.getGoodsInfo()!=null&&clearWeedResult.getGoodsInfo().size() > 1) {
                        //滑动到底部加载更多
                        trim = etCoinShop.getText().toString().trim();
                        pageNum++;
                        if (trim != null && trim.length() > 0) {
                            getSearchData();
                        } else {
                            getData();
                        }
                        isLoading = true;
                        adapter.setFooter_state(1);
                    } else {
                        adapter.setFooter_state(2);
                    }

                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                lastItem = layoutManager.findLastVisibleItemPosition();
            }
        });

        etCoinShop.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {

                if (b) {
                    etHintText.setVisibility(View.GONE);
                    etClear.setVisibility(View.GONE);
                    etTextCancel.setVisibility(View.VISIBLE);
                    etTextCancel.setText("取消");
                }
            }
        });
        etCoinShop.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() > 0) {
                    etClear.setVisibility(View.VISIBLE);
                    etTextCancel.setText("搜索");
                } else {
                    etClear.setVisibility(View.GONE);
                    etTextCancel.setText("取消");
                }
                etHintText.setVisibility(View.GONE);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        adapter.setItemClickListener(this);
    }

    @Override
    protected void processSuccessResult(String response) throws JSONException {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        if (type.equals("cate")) {
            ProjectItemResult itemResult = gson.fromJson(response, ProjectItemResult.class);
            MyApplication.getInstance().setSpValue(itemResult.getSafeobj());
            if (itemResult.getData() != null && itemResult.getData().size() > 0) {
                itemResultList.addAll(itemResult.getData());
            }
            getData();
        } else if (type.equals("data")) {
            clearWeedResult = gson.fromJson(response, ClearWeedResult.class);
            MyApplication.getInstance().setSpValue(clearWeedResult.getSafeobj());
            if (pageNum == 1) {
                clearWeedGoodList.clear();
            }
            if (clearWeedResult.getGoodsInfo() != null && clearWeedResult.getGoodsInfo().size() > 0) {

                clearWeedGoodList.addAll(clearWeedResult.getGoodsInfo());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    storeInfo = jsonObject.optJSONObject("store");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                adapter.setList(clearWeedGoodList, storeInfo);

            } else {
                if (pageNum > 2) {
                    adapter.setFooter_state(2);
                } else {
                    adapter.setFooter_state(0);
                    if (issearch && pageNum < 2) {
                        //搜索不到该商品
                    }
                }
                pageNum--;
                if (pageNum < 1) {
                    pageNum = 1;
                }
            }

            isLoading = false;
            adapter.notifyDataSetChanged();
        }

    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
        MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
        if (baseResponse.getCode() == 1000) {
            adapter.setFooter_state(0);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
        }
    }

    public void setColor(TextView view1, TextView view2, TextView view3) {
        view1.setTextColor(getResources().getColor(R.color.title_red));
        view2.setTextColor(getResources().getColor(R.color.gohere));
        view3.setTextColor(getResources().getColor(R.color.gohere));
    }

    @OnClick({R.id.rl, R.id.clearweed_iv_search, R.id.tv_cate_title, R.id.ll_allCate, R.id.et_text_cancel, R.id.iv_shoper_search, R.id.et_coin_shop, R.id.et_clear, R.id.tv_exchange_recently, R.id.tv_exchange_newest, R.id.tv_exchange_sales})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl:
                break;
            case R.id.tv_cate_title:
                getPopupwindow(tvCateTitle);
                break;
            case R.id.ll_allCate:
                break;
            case R.id.et_text_cancel:
                trim = etCoinShop.getText().toString().trim();
                if (trim.length() > 0) {
                    getSearchData();
                } else {
                    etCoinShop.setText("");
                    etHintText.setVisibility(View.VISIBLE);
                    etClear.setVisibility(View.GONE);
                    etTextCancel.setVisibility(View.GONE);

                    getData();
                }

                //隐藏软键盘
                CommonTool.hideSoft(etCoinShop, ClearWeedExchangeActivity.this);
                break;
            case R.id.iv_shoper_search:
                break;
            case R.id.et_coin_shop:
             /*   etHintText.setVisibility(View.GONE);
                etClear.setVisibility(View.GONE);*/
                etTextCancel.setVisibility(View.VISIBLE);
                etTextCancel.setText("取消");
                break;
            case R.id.et_clear:
                etCoinShop.setText("");
                etHintText.setVisibility(View.VISIBLE);
                etTextCancel.setVisibility(View.VISIBLE);
                etTextCancel.setText("取消");

                CommonTool.hideSoft(etCoinShop, context);
                break;
            case R.id.tv_exchange_recently:
                setColor(tvExchangeRecently, tvExchangeNewest, tvExchangeSales);
                orderby = 1;
                pageNum = 1;
                trim = etCoinShop.getText().toString().trim();
                getOrPost();

                break;
            case R.id.tv_exchange_newest:
                setColor(tvExchangeNewest, tvExchangeRecently, tvExchangeSales);
                orderby = 2;
                pageNum = 1;
                trim = etCoinShop.getText().toString().trim();
                getOrPost();
                break;
            case R.id.tv_exchange_sales:
                setColor(tvExchangeSales, tvExchangeNewest, tvExchangeRecently);
                orderby = 3;
                pageNum = 1;
                trim = etCoinShop.getText().toString().trim();
                getOrPost();
                break;
            case R.id.clearweed_iv_search:
                startAct(ClearWeedSearchActivity.class);
                break;
        }
    }

    private void getPopupwindow(View view) {
        View conView = View.inflate(context, R.layout.pop_reward_window, null);
        conView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        final PopupWindow popupWindow = new PopupWindow(conView, LinearLayout.LayoutParams.MATCH_PARENT, -2, true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        int[] location = new int[2];
        view.getLocationInWindow(location);
        Animation animation = AnimationUtils.loadAnimation(context, R.anim.popupwindow);
        conView.startAnimation(animation);
        popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, location[0], location[1] + view.getWidth() * 1 / 3);
        NoScrollGridView gv_category = (NoScrollGridView) conView.findViewById(R.id.gv_category);

        final TitleCateAdapter cateAdapter = new TitleCateAdapter(context, itemResultList);
        gv_category.setAdapter(cateAdapter);
        gv_category.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                if (i == 0) {
                    cateid = "0";
                } else {
                    cateid = itemResultList.get(i).getId();
                }

                getOrPost();

                tvCateTitle.setText(itemResultList.get(i).getName());
                for (int j = 0; j < itemResultList.size(); j++) {
                    if (j == i) {
                        itemResultList.get(i).setSelect(true);
                    } else {
                        itemResultList.get(j).setSelect(false);
                    }
                }
                cateAdapter.notifyDataSetChanged();
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
            }
        });
    }

    public void getOrPost() {
        if (null != trim && !"".equals(trim)) {
            getSearchData();
        } else {
            getData();
        }
    }

    @Override
    public void onClick(View view, int position) {
        ClearWeedGood clearWeedGood = clearWeedGoodList.get(position);
        Intent intent = new Intent(ClearWeedExchangeActivity.this, ClearWeedDetailActivity.class);
        intent.putExtra("id", clearWeedGood.getId());
        startActivity(intent);
    }
}
